<script lang="ts">
    export default {
        name: 'Shop_address',
    };
</script>

<script setup lang="ts">
    import { computed, onMounted, ref, unref, reactive, watch } from 'vue';
    import { showConfirmDialog, showToast, showLoadingToast, closeToast } from 'vant';
    import { useRouter, useRoute } from 'vue-router'
    import API_HOME from '@/apis/home';
    import { useI18n } from 'vue-i18n';
    import { useShopNav } from '@/store/modules/app';
    const { t } = useI18n();
    let isMobile = ref(false);
    let router = useRouter()
    let route = useRoute()
    let isAddPage = ref(false)
    const appStore = useShopNav();
    onMounted(() => {
        window.addEventListener('resize', checkDevice);
        checkDevice(); // 初始检测
        if (route.path === '/user') {
            isAddPage.value = true
        }
        getCountryList()
        getAddressList()
        getDefaultAddress()
    });
    const searchResult = ref([]);
    // 使用 ref 而 computed是只读的
    const chosenAddressId = ref(appStore.getAddressId);
    // 响应式更新，添加一个 watch
    watch(() => appStore.getAddressId, (newVal) => {
        chosenAddressId.value = newVal;
    });
    let showPicker = ref(false)
    const searchText = ref('');
    let countryList = ref([])
    // 检测设备函数
    const checkDevice = () => {
        isMobile.value = window.innerWidth <= 768;
    };
    // 过滤后的城市列表
    const filteredCityList = computed(() => {
        if (!searchText.value) return countryList.value;
        return countryList.value.filter(city =>
            city.name.includes(searchText.value)
        );
    });
    const addressList = ref([]);
    const disabledList = [];
    const show = ref(false);
    let isEdit = ref(false);
    const from = reactive({
        consignee: '',
        mobile: '',
        address: '',
        country: '',
        country_code: '',
        is_default: false,
        province_name: '',
        city_name: '',
        district_name: '',
    })
    // 获取国家列表
    let getCountryList = async () => {
        let res = await API_HOME.addressCountry()
        if (res.code == 1) {
            countryList.value = res.data
        }
    }
    // 获取地址列表
    let getAddressList = async () => {
        let res = await API_HOME.addressList()
        if (res.code == 1) {
            addressList.value = res.data.data
        }
    }
    // 提交地址
    const onSubmit = async (values) => {
        if (from.id) {
            let res = await API_HOME.addressEdit(from)
            if (res.code == 1) {
                getAddressList()
                resetForm()
                showToast(res.msg);
            }
        } else {
            let res = await API_HOME.addressAdd(from)
            if (res.code == 1) {
                getAddressList()
                resetForm()
                showToast(res.msg)
            }
        }
        show.value = false;

    };
    // 编辑地址
    const handleEdit = async (item, index) => {
        isEdit.value = true;
        show.value = true;
        Object.assign(from, item);
        let countrySelect = countryList.value.find((i) => {
            return i.code === from.country_code
        })
        if (countrySelect) {
            from.country = countrySelect.name
        }
    };
    const handleAdd = () => {
        isEdit.value = false;
        show.value = true;
    }
    // 删除地址
    const handleDelete = (item) => {
        showConfirmDialog({
            title: t('home.ConfirmDelete'),
            message: t('home.AreyousureAddress'),
        }).then(async () => {
            let res = await API_HOME.addressDelete({
                id: item.id
            })
            if (res.code == 1) {
                getAddressList()
                showToast(res.msg);
            }
        });
    };
    // 获取默认地址
    let getDefaultAddress = async () => {
        let res = await API_HOME.addressDfault()
        if (res.code == 1) {
            appStore.setAddressId(res.data.id)
        }
    }
    // 重置表单
    const resetForm = () => {
        from.consignee = '';
        from.mobile = '';
        from.country_code = '';
        from.country = '';
        from.address = '';
        from.province_name = '';
        from.city_name = '';
        from.district_name = '';
        from.is_default = false;
        from.id = undefined
    };
    // 确认选择
    let onConfirm = (e) => {
        from.country_code = e.selectedOptions[0].code
        from.country = e.selectedOptions[0].name
        showPicker.value = false
    }
    const handleSearch = () => {
        // 添加防抖逻辑
    };
    // 切换地址
    let changeRadio = (e) => {
        appStore.setAddressId(e)
        if (!unref(isAddPage)) {
            appStore.getCarCheckList()
        }
    }
</script>

<template>
    <div>
        <div class="title">
            <div>
                {{t('home.YourAddress')}}
            </div>
            <div>
                <div class="addBtn">
                    <van-button type="primary" size="small" @click="handleAdd">{{t('home.NewAddress')}}</van-button>
                </div>
            </div>
        </div>
        <div class="address-list" :class="isAddPage?'h50':'h25'">
            <div v-for="item in addressList" :key="item.id">
                <div class="flex al-center jus-bet">
                    <div @click="changeRadio(item.id)" class="address_item">
                        <van-radio v-model="chosenAddressId" :name="item.id" class="van-address-item__radio"
                            v-if="!isAddPage" />
                        <div class="item-info">
                            <div class="address_name">
                                <span>{{ item.consignee }}</span>

                                <van-tag v-if="item.is_default" type="primary" size="small" class="margin6">
                                    {{ item.is_default ? t('home.DefaultAddress') : '' }}
                                </van-tag>
                            </div>
                            <div><span>{{ item.mobile }}</span></div>
                            <!-- <div class="email-row f14" v-if="item.email">
                                                    <van-icon name="envelop-o" class="email-icon" />
                                                    <span class="email-text">{{ item.email }}</span>
                                                </div> -->
                            <!-- <div>{{item.country_code}}</div> -->
                            <div class="f14">{{ item.address }}</div>
                        </div>
                    </div>
                    <div class="item_icon">
                        <van-icon name="edit" color="#b19c99" size="26" class="edit-icon" style="margin-right: 10px;"
                            @click="handleEdit(item, index)" />
                        <van-icon name="delete" color="#e74032" size="26" class="delete-icon"
                            @click="handleDelete(item)" />
                    </div>
                </div>
                <van-divider />
            </div>
        </div>
        <van-dialog v-model:show="show" :title="t('home.address')" :showConfirmButton="false" closeOnClickOverlay
            @close="resetForm">
            <van-form @submit="onSubmit">
                <van-cell-group inset>
                    <van-field v-model="from.consignee" name="consignee" :label="t('home.consignee')"
                        :placeholder="t('home.please')+t('home.consignee')"
                        :rules="[{ required: true, message: t('home.please')+t('home.consignee') }]" />
                    <van-field v-model="from.mobile" name="mobile" :label="t('home.phone')"
                        :placeholder="t('home.please')+t('home.phone')"
                        :rules="[{ required: true, message: t('home.please')+t('home.phone')}]" />
                    <van-field v-model="from.country" is-link readonly name="country" :label="t('home.country')"
                        :placeholder="t('home.please')+t('home.country')" @click="showPicker = true" />
                    <van-field v-model="from.province_name" name="province_name" :label="t('home.state')"
                        :placeholder="t('home.please')+t('home.state')" />
                    <van-field v-model="from.city_name" name="city_name" :label="t('home.city')"
                        :placeholder=" t('home.please')+t('home.city')" />
                    <van-field v-model="from.district_name" name="district_name" :label="t('home.area')"
                        :placeholder="t('home.please')+t('home.area')" />
                    <van-field v-model="from.address" name="address" :label="t('home.DetailedAddress')"
                        :placeholder="t('home.please')+t('home.DetailedAddress')" rows="2" autosize type="textarea"
                        :rules="[{ required: true, message: t('home.please')+t('home.DetailedAddress') }]" />
                    <van-field name="switch" :label="t('home.SetasdefaultdeliveryAddress')" label-width="120px">
                        <template #input>
                            <van-switch v-model="from.is_default" />
                        </template>
                    </van-field>
                </van-cell-group>
                <div style="margin: 16px;">
                    <van-button round block type="primary" native-type="submit">
                        {{t('home.submit')}}
                    </van-button>
                </div>
            </van-form>
        </van-dialog>
        <!-- 国家选择 -->
        <van-popup v-model:show="showPicker" :position="isMobile?'bottom':'center'"
            :style="isMobile ? { height: '40%', width: '100%' } : { width: '30%', height: '40%' } ">
            <van-search v-model="searchText" :placeholder="t('home.SearchCountry')"
                @update:model-value="handleSearch" />
            <van-picker :columns="filteredCityList" :columns-field-names="{ text: 'name', value: 'code' }"
                @confirm="onConfirm" @cancel="showPicker = false" />

        </van-popup>

    </div>
</template>

<style lang="less" scoped>
    .h25 {
        height: 25vh;
    }

    .h50 {
        height: 50vh;
    }

    .title {
        margin: 6px;
        font-size: 18px;
        font-weight: 600;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .address-list {

        overflow-y: scroll;

        .address_item {
            display: flex;
            align-items: center;

            .item-info {
                margin-left: 16px;
                flex: 1;

                .address_name {
                    padding: 6px 0;
                }
            }

        }

        .item_icon {
            padding-right: 10px
        }
    }

    .addBtn {
        margin: 20px;
    }

    @media screen and (max-width: 768px) {
        .title {
            font-size: 18px;
        }



    }
</style>